package juc;

class Broker{
    private Integer product=0;//商品

    //卖货
    public synchronized void getProduct() {
        while (product<=0){
            System.out.println("仓库缺货");
            try {
                wait();//等待仓库有货
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("卖出:1，还剩:" + --product);
        notifyAll();//通知生产者，仓库有位置放货

    }

    //进货
    public synchronized void setProduct() {
        while (product>=1){
            System.out.println("仓库已满");
            try {
                wait();//等待仓库有空位置
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("进货:1，还剩:"+ ++product);
        notifyAll();//通知消费者，仓库有货了

    }
}

class Productor implements Runnable{
    private Broker broker;
    public Productor(Broker broker){
        this.broker = broker;
    }
    @Override
    public void run() {
        for (int i=0; i<20; i++){
            broker.setProduct();
        }
    }
}

class Consumer implements Runnable{
    private Broker broker;
    public Consumer(Broker broker){
        this.broker = broker;
    }
    @Override
    public void run() {
        for (int i=0; i<20; i++){
            broker.getProduct();
        }
    }
}

public class ProductorAndConsumer {
    public static void main(String[] args) {
        Broker broker = new Broker();
        Productor productor = new Productor(broker);
        Consumer consumer = new Consumer(broker);
        new Thread(productor).start();
        new Thread(consumer).start();
    }
}
